package com.my.biao.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.my.biao.constant.NetWorkConstant;
import com.my.biao.util.CacheActivity;

/**
 * 项目名称：BaseActivity
 * 创建人：mwb
 * 创建时间：2018/7/25 17:57
 */

public abstract class BaseActivity extends AppCompatActivity {
    private final String TAG = "BiAo";
    private Bundle savedInstanceState;

    /*** 网络变化广播相关内容 */
    private IntentFilter intentFilter;
    private NetWorkChangeReceiver netWorkChangeReceiver;

    /*** 网络变化广播相关内容 */

    @Override

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.savedInstanceState = savedInstanceState;

        if (!CacheActivity.activityList.contains(this)) {
            CacheActivity.addActivity(this);
        }

        setContentView();
        initData();
        initTheme();
        initBar();
        initView();
        initListener();
        httpData();
    }

    public void initTheme() {
    }

    public void initBar() {

    }

    public void initView() {

    }

    public void initData() {

    }

    public void initListener() {

    }

    public void httpData() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        netWorkChangeReceiver = new NetWorkChangeReceiver();
        registerReceiver(netWorkChangeReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(netWorkChangeReceiver);
    }

    protected abstract void setContentView();

    /**
     * 网络变化广播监听
     */
    public class NetWorkChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            ConnectivityManager connectivityManager =
                    (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isAvailable()) {
                netWorkChangeState(NetWorkConstant.BIAO_NETWORK_AVAILABLE);
            } else {
                netWorkChangeState(NetWorkConstant.BIAO_NETWORK_UNAVAILABLE);
            }
        }
    }

    /**
     * 网络状态
     *
     * @param i
     * @return
     */
    public int netWorkChangeState(int i) {
        return i;
    }
}
